﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using service_desk_blred.Models;
using System.Web.Routing;
using System.Web.Security;
using System.Web.UI;
using service_desk_blred.Utils;

namespace service_desk_blred.Controllers
{
    [HandleError]
    public class InicioController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public UsuarioService UsuarioService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new ControleDeAcessoService(); }
            if (UsuarioService == null) { UsuarioService = new UsuarioService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Inicio/Login
        // **************************************

        public ActionResult Login()
        {
            UsuarioModel user = (UsuarioModel) Session["USUARIO_LOGADO"];

            if (user == null) {
                FormsService.SignOut();
                return View();
            }

            //Verifica se Usuário está logado, se sim, direciona para devida página, senão manda para a pág de Login
            if (Request.IsAuthenticated)
            {
                //Verifica o tipo de usuário.
                String userName = User.Identity.Name;

                if (Roles.IsUserInRole(userName, "analista"))
                {
                    return RedirectToAction("Index", "Analista");
                }

                else if (!Roles.IsUserInRole(userName, "cliente"))
                {
                    return RedirectToAction("EscolheCategoria", "Chamado");
                }


                else if (!Roles.IsUserInRole(userName, "cliente_gestor"))
                {
                    return RedirectToAction("EscolheCategoria", "Chamado");
                }


                else if (!Roles.IsUserInRole(userName, "gestorti"))
                {
                    return RedirectToAction("Index", "Analista");
                }
                else
                {
                    return View();
                }

            }
            else
            {
                return View();
            }


        }

        [HttpPost]
        public ActionResult Login(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {

                ResponseInfo response = UsuarioService.ValidarUsuario(model.Login, model.Senha);

                if (response.isSuccess())
                {

                    Session["USUARIO_LOGADO"] = (UsuarioModel)response.objResponse;

                    FormsService.SignIn((UsuarioModel)response.objResponse, false);

                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Analista");
                    }
                }
                else
                {
                    ModelState.AddModelError("", response.descricao);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Usuario/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();
            return RedirectToAction("Login", "Inicio");
        }

        // **************************************
        // URL: /Inicio/EsqueciSenha
        // **************************************

        public ActionResult EsqueciSenha()
        {
            return View();
        }

        [HttpPost]
        public ActionResult EsqueciSenha(EsqueciSenhaModel model)
        {
            if (ModelState.IsValid)
            {

                if (UsuarioService.VerificaRecuperacaoDeSenha(model.Email))
                {

                    if (EmailUtil.enviarEmail(model.Email, "recuperarEmail@blred.com.br", "Recuperar Senha", "Sua nova senha é: BLRED@123"))
                    {
                        return RedirectToAction("SucessoSenha", "Inicio");
                    }
                    else
                    {

                        ModelState.AddModelError("", "Erro ao recuperar senha");

                        return View();

                    }
                }
                else
                {
                    ModelState.AddModelError("", "Email não encontrado na base");
                    return View();
                }

            }
            else
            {

                ModelState.AddModelError("", "Erro ao recuperar Senha");

                return View();
            }
        }


        public ActionResult SucessoSenha()
        {
            return View();
        }



    }
}